package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.cloud.client.discovery.DiscoveryClient;

import java.util.List;

@Controller
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;
    @Autowired
    private DiscoveryClient discoveryClient;
    @ResponseBody
    @GetMapping(value = "/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        //获得服务清单列表(对外暴露的微服务名称)
        for (String service:services){
            log.info("*****element:"+service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        //具体微服务的详细信息
        for(ServiceInstance instance:instances){
            log.info("主机id:"+instance.getServiceId());
            log.info("主机名称:"+instance.getHost());
            log.info("端口号:"+instance.getPort());
            log.info("URI地址:"+instance.getUri());
        }
        return discoveryClient;
    }
    @ResponseBody
    @PostMapping(value = "/payment/create")
    public CommonResult create(@RequestBody Payment payment){
        int i = paymentService.create(payment);
        log.info("*******插入结果："+i);
        if (i>0){
            return new CommonResult(200,"机器【"+serverPort+"】插入数据成功",i);
        }else {
            return new CommonResult(444,"机器【"+serverPort+"】插入失败");
        }
    }
    @ResponseBody
    @GetMapping(value = "/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id")Long id){
        Payment payment= paymentService.getPaymentById(id);
        log.info("*******查询结果："+(payment!=null));
        if(payment!=null){
            return new CommonResult(200,"机器【"+serverPort+"】查询数据成功",payment);
        }else {
            return new CommonResult(444,"机器【"+serverPort+"】查不到数据id="+id);

        }
    }
    @ResponseBody
    @GetMapping(value = "/payment/lb")
    public int lb(){
        return 8002;
    }
    @ResponseBody
    @GetMapping(value = "/payment/timeout")
    public String paymentTimeout(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
}
